import { Button, Icon, Image, ScrollView, Text, View } from '@tarojs/components';
import {
  hideLoading,
  previewImage,
  redirectTo,
  showLoading,
  showModal,
  showToast,
  useEffect,
  useRouter,
  useState
} from '@tarojs/taro';
import Layout from '../../components/Layout';
import XEditor from '../../components/XEditor';
import XList from '../../components/XList';
import XRow from '../../components/XRow';
import { CacheTemp } from '../../constant/cache';
import baseService from '../../utils/baseService';
import upload from '../../utils/upload';
import { getCache } from '../../utils/utils';

const Comment = () => {
  const [isShowEditor, setIsShowEditor] = useState(false);
  const [bug, setBug] = useState({});
  const [curr, setCurr] = useState({});
  const [files, setFiles] = useState([]);
  const {
    params: { id }
  } = useRouter();

  useEffect(() => {
    const bug = getCache(CacheTemp, true);
    setBug(bug);
  }, []);

  const onCommitEditor = ({ html, text }) => {
    setIsShowEditor(false);
    setCurr({ ...curr, comment: html });
  };

  const onUpload = () => {
    upload({})
      .then((url) => {
        const fs = [...files];
        fs.push({
          url,
          html: `<img src="${url}" style="max-width:100%;height:auto;display:block;">`
        });
        setFiles(fs);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  const onPreview = (url) => {
    previewImage({
      current: url,
      urls: files.map((x) => x.url)
    });
  };

  const onCloseImg = (index) => {
    showModal({ title: '操作提示', content: '确定要删除图片吗' }).then(({ confirm }) => {
      if (confirm) {
        const fs = [...files];
        fs.splice(index, 1);
        setFiles(fs);
      }
    });
  };

  const onFocusContent = () => {
    setIsShowEditor(true);
  };

  const onSave = () => {
    showLoading({ title: '操作中' });
    const url = `/action-comment-task-${id}.html`;
    const comment =
      curr['comment'] +
      (files.length ? '<br>[图片附件]<br>' + files.map((x) => x.html).join('<br>') : '') +
      '<br />来自oa的备注';
    baseService
      .post(url, { comment }, { isForm: true })
      .then(({ data }) => {
        showToast({ title: '保存成功' });
        redirectTo({ url: 'detail?id=' + id });
      })
      .catch(() => {
        showToast({ title: '保存失败', icon: 'none' });
        hideLoading();
      });
  };

  return (
    <Layout>
      {isShowEditor && <XEditor onCommit={onCommitEditor} value={curr['comment'] || ''}></XEditor>}
      <ScrollView
        scrollY={true}
        style={{ height: 'calc(100vh - 50px - env(safe-area-inset-bottom))' }}
      >
        <XList isCustomize={true}>
          <View style={{ display: 'flex', flexWrap: 'wrap' }}>
            <Text decode={true}> {bug['title']}</Text>
          </View>
        </XList>
        <XList isCustomize={true} isMini={true}>
          <XRow>
            <View>上传图片</View>
            <View style={{ display: 'flex', alignItems: 'center' }}>
              <Button size="mini" type="warn" onClick={onUpload}>
                上传
              </Button>
            </View>
          </XRow>
          <View style={{ display: 'flex', alignItems: 'center' }}>
            {files.map((x, xIndex) => (
              <View key={x.url} style={{ marginRight: '2px', position: 'relative' }}>
                <Image
                  src={x.url}
                  style={{ width: '60px', height: '60px' }}
                  onClick={onPreview.bind(this, x)}
                ></Image>
                <Icon
                  type="clear"
                  color="red"
                  size="16"
                  style={{ position: 'absolute', right: '0' }}
                  onClick={onCloseImg.bind(this, xIndex)}
                ></Icon>
              </View>
            ))}
          </View>
        </XList>
        <XList isCustomize={true} onClick={onFocusContent}>
          <View style={{ minHeight: '100px' }}>
            <wxparser rich-text={curr['comment'] || '点击输入说明备注'} />
          </View>
        </XList>
      </ScrollView>
      <View
        style={{
          position: 'fixed',
          bottom: 0,
          marginBottom: 0,
          width: '100%',
          background: '#23d1a5',
          color: '#fff',
          zIndex: 10000,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          paddingTop: '14px',
          paddingBottom: 'calc(14px + env(safe-area-inset-bottom))'
        }}
        onClick={onSave}
      >
        保存
      </View>
    </Layout>
  );
};
Comment.config = {
  navigationBarTitleText: '添加Task备注',
  disableScroll: true,
  usingComponents: {
    wxparser: 'plugin://wxparserPlugin/wxparser'
  }
};
export default Comment;
